<template>
	<div class="main">
		<!-- 登录弹窗 -->
		<UserLoginDialog v-if="dialogUserLoginVisible" @login="handleLogin" @close-dialog="closeLoginDialog"></UserLoginDialog>
		<div class="home-content">
			<div class="sidebar">
				<el-avatar :size="35" :src="logoPath" style="margin-top: 35px" fit="cover" />
				<el-tooltip effect="dark" content="开启新对话" placement="top">
					<div class="add_chat" @click="resetChat()">
						<div class="chat_clear"></div>
					</div>
				</el-tooltip>
			</div>
			<div class="content">
				<el-scrollbar ref="scrollbarRef" class="scrollbar" @end-reached="loadMore()">
					<div class="grid-container">
						<div class="grid-left"></div>
						<div class="grid-center">
							<!-- 描述部分 -->
							<transition name="fade">
								<div class="part_one" v-if="showAiChat">
									<div class="first" style="margin-top: 50px">
										<el-avatar :size="45" :src="logoPath" fit="cover" />
										<el-text class="mx-1" size="large" style="color: #000; font-size: 22px; margin-left: 10px">我是小美同学，很高兴见到你！</el-text>
									</div>
									<div class="second" style="margin-top: 50px">
										<el-text style="text-align: left; font-size: 16px"
											>您好，我是您的人工智能大模型——小美同学，现在的我能够学习和理解人类的语言，进行多轮对话，回答问题，高效帮助您获取店铺信息、业绩数据、美业知识等，快来和我聊聊天吧！如果您不确定从哪里开始，可以试试这样问我。</el-text
										>
									</div>
									<el-divider content-position="left" style="margin-top: 30px">
										<el-text style="text-align: left; font-size: 16px">您可以这样问我</el-text>
									</el-divider>
									<div class="third" v-for="(item, index) in recommendQuestionList" :key="index">
										<div class="question" @click="openQuestion(item.title)">
											{{ item.title }}
										</div>
									</div>
								</div>
							</transition>
							<!-- chat-ai 部分 -->
							<div class="part_two" v-for="(item, index) in userChatAnswerList" :key="index">
								<!-- 用户 -->
								<div class="user_question">
									<div class="question_area">
										<div class="ask_content">{{ item.question }}</div>
										<div class="ai_user_func" v-if="!item.loading">
											<div>
												<el-tooltip effect="dark" content="复制" placement="top">
													<div class="ask_lay" @click="copyText(item.question)">
														<div class="ask_copy"></div>
													</div>
												</el-tooltip>
											</div>
											<div style="margin-left: 5px">
												<el-tooltip effect="dark" content="修改" placement="top">
													<div class="edit_lay" @click="editText(item.question)">
														<div class="edit_copy"></div>
													</div>
												</el-tooltip>
											</div>
										</div>
									</div>
								</div>
								<!-- ai -->
								<div class="ai_background">
									<!-- 加载效果 -->
									<div class="loading" v-if="item.loading">
										<el-avatar :size="25" :src="logoPath" fit="cover" />
										<div style="color: #518cff; font-size: 16px; margin-left: 5px">小美同学思考中</div>
										<!-- <div class="loader_circle"></div> -->
										<div class="three_dot">
											<div class="loader_dot">
												<span>.</span>
												<span>.</span>
												<span>.</span>
											</div>
										</div>
									</div>
									<!-- 文本展示 -->
									<div>
										<Markdown :source="item.answer" class="markdown"></Markdown>
									</div>
									<!-- 功能按钮 -->
									<div class="ai_bottom" v-if="!item.loading">
										<div>
											<el-tooltip effect="dark" content="复制" placement="top">
												<div class="ai_copy_lay" @click="copyText(item.answer)">
													<div class="go_copy"></div>
												</div>
											</el-tooltip>
										</div>
										<div style="margin-left: 5px">
											<el-tooltip effect="dark" content="重新生成" placement="top">
												<div class="ai_refresh_lay" @click="refreshQuestion(item.question)">
													<div class="go_refresh"></div>
												</div>
											</el-tooltip>
										</div>
									</div>
								</div>
							</div>
							<div class="part_three"></div>
							<div class="part_four"></div>
						</div>
						<div class="grid-right"></div>
					</div>
				</el-scrollbar>
			</div>
		</div>
		<div class="user-input">
			<div class="chat-input-left">
				<el-dropdown placement="top-start" trigger="click">
					<el-avatar :size="35" :src="shouUserHeader()" style="margin-bottom: 30px" />
					<template #dropdown>
						<el-dropdown-item style="padding: 10px">{{ showUserName() }}</el-dropdown-item>
						<el-dropdown-item :icon="showUserLoginOrOutIcon()" style="padding: 10px" @click="handlerUser()">{{ showUserLoginOrOut() }}</el-dropdown-item>
					</template>
				</el-dropdown>
			</div>
			<div class="chat-input">
				<div class="chat-grid-left"></div>
				<div class="chat-grid-center">
					<div class="chat-content">
						<input v-model="input" @keyup.enter="sendInputAnswer()" class="chat-input-content" placeholder="给小美同学发消息" />
						<div class="chat-send">
							<div class="chat_type">
								<div class="chat_new" @click="resetChat">
									<img class="image_new_chat" :src="addNewChatPath" />
									<div class="chat_text">开启新对话</div>
								</div>
							</div>
							<el-tooltip effect="dark" :disabled="disabled()" :content="tooltipContent()" placement="top">
								<div :class="sendState()" @click="sendOrStopAnswer()" style="margin-right: 5px; margin-bottom: 5px"></div>
							</el-tooltip>
						</div>
					</div>
				</div>
				<div class="chat-grid-right"></div>
			</div>
		</div>
	</div>
</template>

<script setup>
import CryptoJS from "crypto-js";
import axios from "axios";
import Markdown from "vue3-markdown-it";
import "highlight.js/styles/a11y-dark.css";
import ChatQuestion from "@/models/chat/ChatQuestion";
import logoPath from "@/assets/logo.png";
import userPath from "@/assets/user.png";
import addNewChatPath from "@/assets/new_chat_icon.png";
import { Avatar, SwitchButton } from "@element-plus/icons-vue";

import { ref, reactive, onMounted, computed, nextTick } from "vue";
//引入登录弹窗
import UserLoginDialog from "@components/UserLoginDialog.vue";
/* chat-ai相关 */
const showAiChat = ref(true);
//回答问题列表
const userChatAnswerList = ref([]);
//推荐问题列表
const recommendQuestionList = ref([]);
//提问问题列表(只保存最新两个)
const askQuestionList = ref([]);
//解析后的完整回答
let answerText = "";
//回答(可以是全部 可以是部分)
let answerPart = "";
//原数据 带data 完整数据
let buffer = "";
//提问的问题
let question = "";
//打印机收集器
let indexChar = 0;
//是否正在操作ai数据
let isOperateChatData = false;
//数据流还在继续输出(后台返回的数据流)
let isLoadingChatData = false;
//打印的数据流是否正在继续
let isPrintChatData = ref(false);
//用户点击了停止
let isLoadingChatDataStop = false;
let indexChat = 0;
//间隔执行器Id
let intervalId = null;
const input = ref("");
/* 用户登录相关 */
const dialogUserLoginVisible = ref(false);
const userInfo = ref({
	userId: "",
	shopId: "",
	token: "",
});

/* 测试 */
function test() {
	/* let person = {
		name: "张三",
		age: 30,
		skills: ["JavaScript", "HTML", "CSS"],
	};
	let personString = JSON.stringify(person);
	localStorage.setItem("personData", personString);

	// 从localStorage读取JSON数据并转换回对象
	let storedPersonString = localStorage.getItem("personData");
	let storedPerson = JSON.parse(storedPersonString);
	console.log(storedPerson); // 输出: { name: "张三", age: 30, skills: ["JavaScript", "HTML", "CSS"] } */
	const chatModel = new ChatQuestion(true, "", "");
	chatModel.loading = true;
	chatModel.question = "我爱你";
	chatModel.answer = "";
	userChatAnswerList.value.push(chatModel);
	nextTick(() => {
		if (!scrollbarWrapEl) {
			scrollbarWrapEl = getScrollbarWrapElement();
		}
		if (scrollbarWrapEl) {
			// 滚动到底部
			//scrollbarWrapEl.scrollTop = scrollbarWrapEl.scrollHeight;
			//或者使用平滑滚动
			scrollbarWrapEl.scrollTo({
				top: scrollbarWrapEl.scrollHeight,
				behavior: "smooth",
			});
		}
	});
}

/* 钩子函数 */
onMounted(() => {
	nextTick(() => {
		scrollbarWrapEl = getScrollbarWrapElement();
		scrollbarWrapEl.addEventListener("scroll", handleScroll);
		loadUserData();
	});
});

//卸载组件前执行清理工作
onBeforeUnmount(() => {});
/* 滚动条相关 */
const scrollbarRef = ref(null);
let scrollbarWrapEl = null;
let scrollTimer = null;
const scrollTop = ref(0);
const scrollHeight = ref(0);
const clientHeight = ref(0);
const isAutoScroll = ref(true);
// 获取滚动容器 DOM 元素
const getScrollbarWrapElement = () => {
	if (scrollbarRef.value) {
		// ElementPlus Scrollbar 组件内部的滚动容器
		return scrollbarRef.value.$el.querySelector(".el-scrollbar__wrap");
	}
	return null;
};

//触发滚动事件
function handleScroll(e) {
	//const { scrollTop, scrollHeight, clientHeight } = e.target
	//scrollTop当前滚动高度
	//scrollHeight可滚动内容的总高度
	//clientHeight容器的可见高度
	//console.log("scrollTop：", scrollTop)
	//console.log("scrollHeight", scrollHeight)
	//console.log("clientHeight", clientHeight)
	/* scrollTop.value = e.target.scrollTop;
	scrollHeight.value = e.target.scrollHeight;
	clientHeight.value = e.target.clientHeight;
	//判断是否滚动到底部(允许100px误差)
	const isAtBottom = scrollTop.value + clientHeight.value >= scrollHeight.value - 100;
	if (!isAtBottom && isAutoScroll.value) {
		isAutoScroll.value = false;
		console.log("自动滚动结束了");
	} else {
		//用户再次滚动到底部，继续自动滚动
		isAutoScroll.value = true
		console.log("真的到底了");
	} */
}

//滚动条滚动到了底部
function loadMore() {
	console.log("end-reached");
}

//开始自动滚动
function startAutoScroll() {
	isAutoScroll.value = true;
	stopAutoScroll();
	scrollTimer = setInterval(scrollToBottom, 1000);
}

function stopAutoScroll() {
	if (scrollTimer !== null) {
		clearInterval(scrollTimer);
		scrollTimer = null;
	}
}

//滚动条滚动到底部
function scrollToBottom() {
	if (isAutoScroll.value) {
		nextTick(() => {
			if (!scrollbarWrapEl) {
				scrollbarWrapEl = getScrollbarWrapElement();
			}
			if (scrollbarWrapEl) {
				// 滚动到底部
				//scrollbarWrapEl.scrollTop = scrollbarWrapEl.scrollHeight;
				//或者使用平滑滚动
				scrollbarWrapEl.scrollTo({
					top: scrollbarWrapEl.scrollHeight,
					behavior: "smooth",
				});
			}
		});
	}
}

/* chat-ai相关 */
//重置基础量变
function resetVariables() {
	indexChar = 0;
	buffer = "";
	answerText = "";
	answerPart = "";
	indexChar = 0;
	buffer = "";
	input.value = "";
	isOperateChatData = false;
	isLoadingChatData = false;
	isLoadingChatDataStop = false;
	isPrintChatData.value = false;
	isAutoScroll.value = true;
	scrollTop.value = 0;
	scrollHeight.value = 0;
	clientHeight.value = 0;
	if (intervalId != null) {
		clearInterval(intervalId);
		intervalId = null;
	}
}
//重置页面
function resetChat() {
	if (userChatAnswerList.value.length == 0) {
		ElMessage.primary("当前已在新的会话中");
	} else {
		resetVariables();
		userChatAnswerList.value.length = 0;
		showAiChat.value = true;
		stopAutoScroll();
	}
}

function sendOrStopAnswer(){
	if (isPrintChatData.value) {
		stopPrintAnswer();
	}else{
		sendInputAnswer();
	}
}

//发送输入的问题
function sendInputAnswer() {
	if (input.value) {
		//如果正在打印输出流
		if (isPrintChatData.value) {
			stopPrintAnswer();
		}
		openQuestion(input.value);
	}
}

//刷新问题，重新提问
function refreshQuestion(question) {
	if (isPrintChatData.value) {
		stopPrintAnswer();
	}
	if (input.value) {
		input.value = "";
	}
	openQuestion(question);
}

//停止输出打印
function stopPrintAnswer() {
	stopAutoScroll();
	isLoadingChatDataStop = true;
}

//发送按钮不同状态
function sendState() {
	if (isPrintChatData.value) {
		return "send_stop";
	} else {
		if (input.value) {
			return "send_press";
		} else {
			return "send-normal";
		}
	}
}

//el-tooltip提示
function disabled() {
	if (input.value) {
		return true;
	}
	return false;
}

//el-tooltip提示文字动态修改
function tooltipContent() {
	if (isPrintChatData.value) {
		return "停止生成";
	} else {
		if (!input.value) {
			return "请输入您的问题";
		}
	}
}

//打印chat数据
function printChatData() {
	console.log("Running task...");
	// 先处理需要停止的情况
	if (isLoadingChatDataStop) {
		if (intervalId !== null) {
			clearInterval(intervalId);
			intervalId = null;
		}
		isPrintChatData.value = false;
		stopAutoScroll();
		return; // 停止后续处理
	}
	// 处理打字机效果逻辑
	if (indexChar < answerText.length && isLoadingChatData) {
		if (!isPrintChatData.value) {
			isPrintChatData.value = true;
		}
		answerPart += answerText[indexChar];
		indexChar++;
		userChatAnswerList.value[indexChat].answer = answerPart;
	} else if (!isLoadingChatData) {
		if (indexChar < answerText.length) {
			if (!isPrintChatData.value) {
				isPrintChatData.value = true;
			}
			answerPart += answerText[indexChar];
			indexChar++;
			userChatAnswerList.value[indexChat].answer = answerPart;
		} else {
			//最终结束了
			clearInterval(intervalId);
			intervalId = null;
			isPrintChatData.value = false;
			stopAutoScroll();
			//不是会员了 token失效了等异常情况
			if (isJsonString(answerText)) {
				// 使用 JSON.parse() 解析JSON字符串
				let obj = JSON.parse(answerText);
				// 现在 obj 是一个普通的JavaScript对象
				if (obj.code == 0) {
					let desc = obj.desc;
					userChatAnswerList.value[indexChat].answer = desc;
				}
			}
			userChatAnswerList.value[indexChat].loading = false;
		}
	} else {
		clearInterval(intervalId);
		intervalId = null;
		isPrintChatData.value = false;
		stopAutoScroll();
	}
}

//开始提问
function openQuestion(content) {
	// 处理聊天请求逻辑
	if (showAiChat.value) {
		showAiChat.value = false;
	}
	// 延迟或立即处理问题
	const handleQuestion = () => {
		question = content;
		const chatModel = new ChatQuestion(true, "", "");
		chatModel.loading = true;
		chatModel.question = content;
		chatModel.answer = "";
		userChatAnswerList.value.push(chatModel);
		nextTick(() => {
			if (!scrollbarWrapEl) {
				scrollbarWrapEl = getScrollbarWrapElement();
			}
			if (scrollbarWrapEl) {
				// 滚动到底部
				//scrollbarWrapEl.scrollTop = scrollbarWrapEl.scrollHeight;
				//或者使用平滑滚动
				scrollbarWrapEl.scrollTo({
					top: scrollbarWrapEl.scrollHeight,
					behavior: "smooth",
				});
			}
			answerQuestion(content);
		});
	};
	// 根据条件决定是否延迟执行
	showAiChat.value ? setTimeout(handleQuestion, 500) : handleQuestion();
}
//回答具体问题
function answerQuestion(question) {
	indexChat = userChatAnswerList.value.length - 1;
	resetVariables();
	// 构建消息列表
	const messageListBean = {
		userMessage: question,
		assistantMessage: "",
	};
	askQuestionList.value.push(messageListBean);
	// 生成签名
	const time = String(Date.now());
	const params = {
		"X-Token": userInfo.value.token,
		"X-UserId": String(userInfo.value.userId),
		"X-Devices": "android",
		"X-Version": "1.2",
		"X-Time": time,
	};
	const sign = getSignContent(params).toUpperCase();
	// 构建请求体
	const paramsBodyOne = {
		userId: String(userInfo.value.userId),
		shopId: String(shopInfo.value.shopId),
	};
	const paramsBodyTwo = {
		messageList: askQuestionList.value,
	};
	const requestJson = toBody(paramsBodyOne, paramsBodyTwo);
	fetch("https://www.iumer.vip/myai-api/app/chat/streamMultipleChat", {
		method: "POST",
		timeout: 600000,
		headers: {
			"Content-Type": "application/json",
			"X-Token": userInfo.value.token,
			"X-UserId": String(userInfo.value.userId),
			"X-Devices": "android",
			"X-Version": "1.2",
			"X-Time": time,
			"X-Sign": sign,
		},
		body: requestJson,
	})
		.then((response) => {
			// 获取响应的可读流
			const reader = response.body.getReader();
			const decoder = new TextDecoder();
			readChatStream(reader, decoder);
		})
		.catch((error) => {
			console.error("Error:", error);
		});
}

async function readChatStream(reader, decoder) {
	while (true) {
		const { done, value } = await reader.read();
		if (done) {
			console.log("数据流处理完成");
			isLoadingChatData = false;
			break;
		}
		// 解码二进制数据为文本
		const blockData = decoder.decode(value, {
			stream: true,
		});
		//console.log("接收到数据块:", blockData);
		buffer += blockData;
		processBuffer(buffer);
	}
}

function processBuffer(content) {
	let result = "";
	const lines = content.split("\n\n");
	for (const line of lines) {
		if (!isEmpty(line)) {
			// 移除"data:"前缀
			const lineData = line.replaceAll("data:", "");
			result += lineData;
		}
	}
	answerText = result;
	if (!isOperateChatData) {
		isOperateChatData = true;
		isLoadingChatData = true;
		intervalId = setInterval(printChatData, 40);
		startAutoScroll();
	}
}

/* 推荐问题 */
function recommendQuestion() {
	const time = String(Date.now());
	const params = {
		"X-Token": userInfo.value.token,
		"X-UserId": String(userInfo.value.userId),
		"X-Devices": "android",
		"X-Version": "1.2",
		"X-Time": time,
	};
	const sign = getSignContent(params).toUpperCase();
	//请求参数
	const paramsBody = {
		userId: String(userInfo.value.userId),
	};
	const requestJson = toBody(paramsBody);
	// 创建AbortController用于取消请求
	const controller = new AbortController();
	axios({
		method: "post",
		url: "https://www.iumer.vip/myai-api/app/ai/selectQuestionList",
		data: requestJson,
		timeout: 10000, // 设置超时时间为10秒
		headers: {
			"content-type": "application/json",
			"X-Token": userInfo.value.token,
			"X-UserId": String(userInfo.value.userId),
			"X-Devices": "android",
			"X-Version": "1.2",
			"X-Time": time,
			"X-Sign": sign,
		},
		signal: controller.signal, // 用于取消请求
	})
		.then((response) => {
			const { code, desc } = response.data;
			if (code == 1) {
				recommendQuestionList.value = response.data.data;
				console.log("recommendQuestionList:", recommendQuestionList.value);
			} else {
				ElMessage(desc);
			}
		})
		.catch((error) => {
			console.error("请求失败:", error.message);
			if (error.code === "ECONNABORTED") {
				console.error("请求超时:", error.config.timeout, "ms");
			} else if (error.response) {
				console.error("状态码:", error.response.status);
				console.error("错误数据:", error.response.data);
			} else if (error.request) {
				console.error("请求已发送但没有收到响应");
			} else {
				console.error("请求配置错误:", error.message);
			}
		});
}
/* 店铺相关 */
const shopInfo = ref({
	shopId: "",
	name: "",
	header: "",
});

/* 店铺相关 */
//获取店信息
async function selectShopInfoDetail() {
	const time = String(Date.now());
	const params = {
		"X-Token": userInfo.value.token,
		"X-UserId": String(userInfo.value.userId),
		"X-Devices": "android",
		"X-Version": "1.2",
		"X-Time": time,
	};
	const sign = getSignContent(params).toUpperCase();
	//请求参数
	const paramsBody = {
		userId: String(userInfo.value.userId),
	};
	const requestJson = toBody(paramsBody);
	// 创建AbortController用于取消请求
	const controller = new AbortController();
	axios({
		method: "post",
		url: "https://www.iumer.vip/myai-api/app/shop/selectShopInfoDetail",
		data: requestJson,
		timeout: 10000, // 设置超时时间为10秒
		headers: {
			"content-type": "application/json",
			"X-Token": userInfo.value.token,
			"X-UserId": String(userInfo.value.userId),
			"X-Devices": "android",
			"X-Version": "1.2",
			"X-Time": time,
			"X-Sign": sign,
		},
		signal: controller.signal, // 用于取消请求
	})
		.then((response) => {
			const { code, desc } = response.data;
			if (code == 1) {
				shopInfo.value = response.data.data;
				recommendQuestion();
			}
			//token失效
			else if (code == -4 || code == -5) {
				clearUserData();
				ElMessageBox.alert("您的账号在其它端登录,请重新登录!", "提示", {
					// if you want to disable its autofocus
					// autofocus: false,
					confirmButtonText: "OK",
					callback: () => {
						console.log("dddddd");
					},
				});
			} else {
				ElMessage(desc);
			}
		})
		.catch((error) => {
			console.error("请求失败:", error.message);
			if (error.code === "ECONNABORTED") {
				console.error("请求超时:", error.config.timeout, "ms");
			} else if (error.response) {
				console.error("状态码:", error.response.status);
				console.error("错误数据:", error.response.data);
			} else if (error.request) {
				console.error("请求已发送但没有收到响应");
			} else {
				console.error("请求配置错误:", error.message);
			}
		});
}

/* 用户登录相关 */
//展示用户头像
function shouUserHeader() {
	if (userInfo.value.userId) {
		return userInfo.value.header;
	} else {
		return userPath;
	}
}
//展示用户名字
function showUserName() {
	if (userInfo.value.userId) {
		return userInfo.value.nickName;
	} else {
		return "请登录账号";
	}
}
//展示用户登录或者退出
function showUserLoginOrOut() {
	if (userInfo.value.userId) {
		return "退出登录";
	} else {
		return "点击登录";
	}
}
//展示用户登录还是退出
function showUserLoginOrOutIcon() {
	if (userInfo.value.userId) {
		return SwitchButton;
	} else {
		return Avatar;
	}
}

//打开用户登录弹窗
function showLoginDialog() {
	dialogUserLoginVisible.value = true;
}

function handlerUser() {
	if (userInfo.value.userId) {
		clearUserData();
		stopPrintAnswer();
		stopAutoScroll();
		resetChat();
	} else {
		showLoginDialog();
	}
}

//关闭用户登录弹窗
function closeLoginDialog() {
	dialogUserLoginVisible.value = false;
}
//用户登录
async function handleLogin(userLoginInfo) {
	clearUserData();
	try {
		console.log("userLoginInfo:", userLoginInfo.username);
		console.log("userLoginInfo:", userLoginInfo.password);
		const time = String(Date.now());
		const params = {
			"X-Token": userInfo.value.token,
			"X-UserId": userInfo.value.user,
			"X-Devices": "android",
			"X-Version": "1.2",
			"X-Time": time,
		};
		const sign = getSignContent(params).toUpperCase();
		console.log("生成的签名 sign:", sign);
		//请求参数
		const paramsBody = {
			phone: userLoginInfo.username,
			loginPassword: getPassWordString(toMD5(userLoginInfo.password)),
		};
		const requestJson = toBody(paramsBody);
		console.log("body请求数据 requestJson:", requestJson);
		// 创建AbortController用于取消请求
		const controller = new AbortController();
		// 发起Axios请求
		const response = await axios({
			url: "https://www.iumer.vip/myai-api/app/user/login",
			method: "POST",
			timeout: 10000,
			data: requestJson,
			headers: {
				"content-type": "application/json",
				"X-Token": userInfo.value.token,
				"X-UserId": String(userInfo.value.userId),
				"X-Devices": "android",
				"X-Version": "1.2",
				"X-Time": time,
				"X-Sign": sign,
			},
			signal: controller.signal, // 用于取消请求
		})
			.then((response) => {
				closeLoginDialog();
				console.log("请求返回的数据:", response.data);
				const { code, desc } = response.data;
				if (code == 1) {
					console.log("userInfoJson:", response.data.data);
					console.log("isJsonString:", isJsonString(response.data.data));
					userInfo.value = response.data.data;
					saveUserData(JSON.stringify(userInfo.value));
					selectShopInfoDetail();
				} else {
					ElMessage(desc);
				}
			})
			.catch((error) => {
				console.error("请求失败:", error);
			});
	} catch (error) {
		console.error("请求失败:", error);
	} finally {
		//最后执行的
	}
}

/**
 * 生成签名内容并计算MD5（同步版本）
 * @param {Object} sortedParams - 已排序的参数对象
 * @returns {string} 签名结果
 */
function getSignContent(sortedParams) {
	let content = "";
	const keys = Object.keys(sortedParams).sort(); // 转换为数组并排序
	let index = 0;

	keys.forEach((key) => {
		const value = sortedParams[key];
		if (!isEmpty(value)) {
			// 检查值是否非空
			content += (index === 0 ? "" : "&") + key + "=" + value;
			index++;
		}
	});

	const secretKey = "&key=A52E7C8B991A4623990F9D99AB96C9B1";
	return toMD5(content + secretKey);
}

/**
 * 计算字符串的 MD5 值（同步版本，使用 crypto-js 库）
 * @param {string} plainText - 输入的明文字符串
 * @returns {string} MD5 哈希值（小写十六进制格式）
 */
function toMD5(plainText) {
	try {
		// 使用 crypto-js 库计算 MD5（需先安装：npm install crypto-js）
		return CryptoJS.MD5(plainText).toString();
	} catch (error) {
		console.error("MD5计算失败:", error);
		return plainText;
	}
}
/**
 * 将两个 Map 合并为 JSON 字符串
 * @param {Object} map - 普通键值对对象
 * @param {Object} listMap - 值可能为复杂对象的键值对
 * @returns {string} 合并后的 JSON 字符串
 */
function toBody(map = {}, listMap = {}) {
	let buffer = "{";

	// 处理普通键值对
	if (map && Object.keys(map).length > 0) {
		for (const [key, val] of Object.entries(map)) {
			buffer += `"${key}":"${val}",`;
		}
	}
	// 处理复杂值的键值对
	if (listMap && Object.keys(listMap).length > 0) {
		for (const [key, val] of Object.entries(listMap)) {
			buffer += `"${key}":${JSON.stringify(val)},`;
		}
	}
	// 移除最后一个逗号或直接闭合
	if (buffer.endsWith(",")) {
		buffer = buffer.slice(0, -1) + "}";
	} else {
		buffer += "}";
	}
	return buffer;
}

function getPassWordString(val) {
	const firstPart = val.substring(0, 2);
	const twoPart = val.substring(2); // JavaScript substring 第二个参数可选，默认到字符串末尾
	return twoPart + firstPart;
}

function saveUserData(jsonString) {
	try {
		localStorage.setItem("userInfo", jsonString);
		console.log("数据存储成功");
	} catch (err) {
		console.error("数据存储失败", err);
	}
}

function loadUserData() {
	try {
		const result = localStorage.getItem("userInfo");
		console.log("result:", result);
		if (result) {
			const parsedData = JSON.parse(result);
			console.log("获取数据成功", parsedData);
			userInfo.value = parsedData;
			selectShopInfoDetail();
		} else {
			console.log("用户数据不存在");
		}
	} catch (err) {
		console.error("获取数据失败", err);
	}
}

function clearUserData() {
	try {
		localStorage.removeItem("userInfo");
		userInfo.value.userId = "";
		userInfo.value.shopId = "";
		userInfo.value.token = "";
		resetVariables();
		userChatAnswerList.value.length = 0;
		showAiChat.value = true;
		stopAutoScroll();
		console.log("数据删除成功");
	} catch (err) {
		console.error("数据删除失败", err);
	}
}

/* 公共方法 */
function isEmpty(value) {
	return value === undefined || value === null || value.toString().trim() === "";
}

function isJsonString(str) {
	try {
		JSON.parse(str);
	} catch (e) {
		return false;
	}
	return true;
}
//复制文本
function copyText(text) {
	try {
		navigator.clipboard.writeText(text);
		ElMessage({
			message: "复制成功",
			type: "success",
		});
	} catch (error) {
		ElMessage.error("复制失败");
	}
}
//编辑文本
function editText(text) {
	input.value = text;
}
</script>

<style lang="scss" scoped>
/* 强制所有 markdown 内容居左 */
.main {
	margin: 0;
	padding: 0;
	width: 100%;
	height: 100vh;
	.home-content {
		display: grid;
		grid-template-columns: 60px 1fr; /* 左边60px，右边占满剩余空间 */
		width: 100%;
		height: 100vh;
		.sidebar {
			display: flex;
			flex-direction: column;
			justify-content: start;
			align-items: center;
			height: 100vh; /* 高度铺满 */
			background-color: #f9fbff;
			.add_chat {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-top: 35px;
				width: 38px;
				height: 38px;
				background-color: white;
				.chat_clear {
					width: 24px;
					height: 24px;
					background-size: cover;
					background-repeat: no-repeat;
					background-image: url("../../assets/add_chat_icon.png");
				}
			}
			.add_chat:hover {
				cursor: pointer;
				border-radius: 6px 6px 6px 6px;
				background-color: #f3f0f0;
			}
		}
		.content {
			display: grid;
			height: 100vh; /* 高度铺满 */
			.scrollbar {
				width: 100%;
				height: 100%;
				background-color: white;
				.grid-container {
					display: grid;
					grid-template-columns: 20% 1fr 20%; /* 三列 */
					.grid-left {
						background-color: transparent;
						height: 100%;
					}
					.grid-center {
						background-color: white;
						height: 100%;
						/* 淡入淡出动画 */
						.fade-enter-from,
						.fade-leave-to {
							opacity: 0;
						}
						.fade-enter-active,
						.fade-leave-active {
							transition: opacity 0.5s ease;
						}

						.part_one {
							display: flex;
							flex-direction: column;
							.first {
								display: flex;
								flex-direction: row;
								align-items: center;
								justify-content: center;
							}
							.second {
								display: flex;
								flex-direction: row;
								align-items: center;
								justify-content: flex-start;
							}
							.third {
								display: flex;
								justify-content: flex-start;
								.question {
									font-size: 16px;
									height: 40px;
									line-height: 40px;
									border-radius: 5px;
									color: #4d6bfe;
								}
							}
						}
						.part_two {
							padding-top: 10px;
							.user_question {
								display: flex;
								margin-top: 30px;
								justify-content: flex-end;
								.question_area {
									display: flex;
									flex-direction: column;
									.ask_content {
										font-size: 16px;
										background-color: #eff6ff;
										padding-right: 15px;
										padding-left: 15px;
										padding-top: 10px;
										padding-bottom: 10px;
										border-radius: 10px 10px 10px 10px;
									}
									.ai_user_func {
										display: flex;
										flex-direction: row;
										margin-top: 5px;
										justify-content: flex-start;
										align-items: center;
										.ask_lay {
											display: flex;
											justify-content: center;
											align-items: center;
											width: 25px;
											height: 25px;
											background-color: white;
											.ask_copy {
												width: 16px;
												height: 16px;
												background-size: cover;
												background-repeat: no-repeat;
												background-image: url("../../assets/copy_icon.png");
											}
										}
										.ask_lay:hover {
											cursor: pointer;
											border-radius: 5px 5px 5px 5px;
											background-color: #f3f0f0;
										}
										.edit_lay {
											display: flex;
											justify-content: center;
											align-items: center;
											width: 25px;
											height: 25px;
											background-color: white;
											.edit_copy {
												width: 16px;
												height: 16px;
												background-size: cover;
												background-repeat: no-repeat;
												background-image: url("../../assets/edit_icon.png");
											}
										}
										.edit_lay:hover {
											cursor: pointer;
											border-radius: 5px 5px 5px 5px;
											background-color: #f3f0f0;
										}
									}
								}
							}

							.ai_background {
								background-color: white;
								padding-top: 20px;
								padding-bottom: 20px;
								border-radius: 12px 12px 12px 12px;

								.loading {
									display: flex;
									align-items: center;

									@keyframes spin {
										0% {
											transform: rotate(0deg);
										}

										100% {
											transform: rotate(360deg);
										}
									}

									.loader_circle {
										border: 2px solid #f3f3f3;
										border-top: 2px solid #3498db;
										border-radius: 50%;
										width: 15px;
										height: 15px;
										animation: spin 1s linear infinite;
										margin-right: 10px;
									}
									.three_dot {
										display: flex;
										padding-top: 10px;
										padding-left: 3px;
										flex-direction: column-reverse;
										.loader_dot {
											display: inline-block;
											font-size: 18px;
											color: #518cff;
											font-weight: normal;
										}
										.loader_dot span {
											animation: blink 1.4s infinite;
										}

										.loader_dot span:nth-of-type(2) {
											animation-delay: 0.2s;
										}

										.loader_dot span:nth-of-type(3) {
											animation-delay: 0.4s;
										}

										@keyframes blink {
											0%,
											100% {
												opacity: 0.2;
											}
											50% {
												opacity: 1;
											}
										}
									}
								}
								.markdown {
									text-align: left;
									font-size: 16px;
								}
								.ai_bottom {
									display: flex;
									flex-direction: row;
									justify-content: flex-start;
									align-items: center;
									.ai_copy_lay {
										display: flex;
										justify-content: center;
										align-items: center;
										width: 25px;
										height: 25px;
										margin-top: 5px;
										background-color: white;
										.go_copy {
											width: 16px;
											height: 16px;
											background-size: cover;
											background-repeat: no-repeat;
											background-image: url("../../assets/copy_icon.png");
										}
									}
									.ai_copy_lay:hover {
										cursor: pointer;
										border-radius: 5px 5px 5px 5px;
										background-color: #f3f0f0;
									}
									.ai_refresh_lay {
										display: flex;
										justify-content: center;
										align-items: center;
										width: 25px;
										height: 25px;
										margin-top: 5px;
										background-color: white;
										.go_refresh {
											width: 16px;
											height: 16px;
											background-size: cover;
											background-repeat: no-repeat;
											background-image: url("../../assets/refresh_icon.png");
										}
									}
									.ai_refresh_lay:hover {
										cursor: pointer;
										border-radius: 5px 5px 5px 5px;
										background-color: #f3f0f0;
									}
								}
							}
						}
						.part_three {
							height: 100px;
							background-color: transparent;
						}
						.part_four {
							height: 150px;
							background-color: transparent;
						}
					}
					.grid-right {
						background-color: transparent;
						height: 100%;
					}
				}
			}
		}
	}
	.user-input {
		position: fixed;
		display: grid;
		grid-template-columns: 60px 1fr; /* 左边60px，右边占满剩余空间 */
		height: 150px;
		width: 100%;
		bottom: 0px;
		z-index: 100;
		background-color: transparent;
		.chat-input-left {
			display: flex;
			flex-direction: column-reverse;
			align-items: center;
			height: 100%;
			.user-info {
				width: 100px;
				height: 200px;
			}
		}
		.chat-input {
			display: grid;
			height: 100%;
			grid-template-columns: 20% 1fr 20%; /* 三列 */
			.chat-grid-left {
				background-color: transparent;
				height: 100%;
			}
			.chat-grid-center {
				background-color: white;
				height: 100%;
				.chat-content {
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					width: 100%;
					height: 120px;
					border-top-left-radius: 20px;
					border-top-right-radius: 20px;
					border-bottom-left-radius: 20px;
					border-bottom-right-radius: 20px;
					padding-right: 5px;
					padding-left: 5px;
					padding-bottom: 5px;
					border: 1px solid #e5e7eb;
					background-color: #f4f5f9;
					border: 1px solid #e5e7eb;
					.chat-input-content {
						height: 60px;
						background-color: transparent;
						margin-top: 3px;
						line-height: 1.5;
						color: #404040;
						padding-left: 10px;
						padding-right: 10px;
						text-align: left;
						justify-self: start; /* 水平居左 */
						font-size: 17px;
						border: none; /* 去掉边框 */
						box-shadow: none; /* 去掉阴影 */
						outline: none; /* 去掉默认的轮廓 */
						border-color: transparent; /* 设置边框颜色为透明 */
					}
					.chat-send {
						display: flex;
						flex-direction: row;
						justify-content: space-between;
						.chat_type {
							display: flex;
							align-items: center;
							.chat_new {
								display: flex;
								justify-content: center;
								align-items: center;
								margin-left: 5px;
								border-radius: 30px;
								padding-right: 15px;
								padding-left: 10px;
								padding-top: 4px;
								padding-bottom: 3px;
								border: 1px solid #c9e1f9;
								background-color: #daeaff;
								.image_new_chat {
									width: 18px;
									height: 18px;
									background-size: cover;
									background-repeat: no-repeat;
								}
								.chat_text {
									font-size: 14px;
									margin-left: 5px;
									text-align: center;
									color: #4c63cb;
									user-select: none; /* 标准方式 */
									-webkit-user-select: none; /* Safari */
									-moz-user-select: none; /* Firefox */
									-ms-user-select: none; /* IE 10及更新版本 */
									pointer-events: none; /* 阻止所有鼠标事件，包括选择 */
								}
							}
							.chat_new:hover {
								border: 1px solid #c5e0fb;
								background-color: #c3d8f4;
								cursor: pointer;
							}
						}
						.send-normal {
							width: 36px;
							height: 36px;
							background-size: cover;
							background-repeat: no-repeat;
							background-image: url("../../assets/send_normal.png");
						}
						.send-normal:hover {
							cursor: not-allowed;
						}
						.send_press {
							width: 36px;
							height: 36px;
							background-size: cover;
							background-repeat: no-repeat;
							background-image: url("../../assets/send_press.png");
						}
						.send_press:hover {
							cursor: pointer;
						}
						.send_stop {
							width: 36px;
							height: 36px;
							background-size: cover;
							background-repeat: no-repeat;
							background-image: url("../../assets/send_stop.png");
						}
						.send_stop:hover {
							cursor: pointer;
						}
					}
				}
			}
			.chat-grid-right {
				background-color: transparent;
				height: 100%;
			}
		}
	}
}
</style>
